{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# mzcn"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "中文版本的matchzoo-py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "本库包是基于matchzoo-py的库包做的二次开发开源项目，MatchZoo 是一个通用的文本匹配工具包，它旨在方便大家快速的实现、比较、以及分享最新的深度文本匹配模型。\n",
    "<br>\n",
    "由于matchzoo-py面向英文预处理较为容易，中文处理则需要进行一定的预处理。为此本人在借鉴学习他人成功的基础上，改进了matchzoo-py包，开发mzcn库包。\n",
    "<br>\n",
    "mzcn库包对中文文本语料进行只保留文本、去除表情、去除空格、去除停用词等操作，使得使用者可以快速进行中文文本语料进行预处理，使用方法和matchzoo-py基本一致。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 快速入手"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 定义损失函数和指标"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "matchzoo version 1.0\n",
      "`ranking_task` initialized with metrics [normalized_discounted_cumulative_gain@3(0.0), normalized_discounted_cumulative_gain@5(0.0), mean_average_precision(0.0)]\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import mzcn as mz\n",
    "print('matchzoo version', mz.__version__)\n",
    "ranking_task = mz.tasks.Ranking(losses=mz.losses.RankHingeLoss())\n",
    "ranking_task.metrics = [\n",
    "    mz.metrics.NormalizedDiscountedCumulativeGain(k=3),\n",
    "    mz.metrics.NormalizedDiscountedCumulativeGain(k=5),\n",
    "    mz.metrics.MeanAveragePrecision()\n",
    "]\n",
    "print(\"`ranking_task` initialized with metrics\", ranking_task.metrics)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 准备输入数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def load_data(tmp_data,tmp_task):\n",
    "\tdf_data = mz.pack(tmp_data,task=tmp_task)\n",
    "\treturn df_data\n",
    "##数据集，并且进行相应的预处理\n",
    "train=pd.read_csv('./data/train_data.csv').sample(100)\n",
    "dev=pd.read_csv('./data/dev_data.csv').sample(50)\n",
    "test=pd.read_csv('./data/test_data.csv').sample(30)\n",
    "train_pack_raw = load_data(train,ranking_task)\n",
    "dev_pack_raw = load_data(dev,ranking_task)\n",
    "test_pack_raw=load_data(test,ranking_task)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 数据集预处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "preprocessor = mz.models.aNMM.get_default_preprocessor()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval:   0%| | 0/95 [00:00<?, ?it/s]Building prefix dict from the default dictionary ...\n",
      "Loading model from cache C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\jieba.cache\n",
      "Loading model cost 1.202 seconds.\n",
      "Prefix dict has been built successfully.\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 95/95 [00:02<00:00, 44.84it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 92/92 [00:00<00:00, 164.08it/s]\n",
      "Processing text_right with append: 100%|████████████████████████████████████████████| 92/92 [00:00<00:00, 46085.75it/s]\n",
      "Building FrequencyFilter from a datapack.: 100%|████████████████████████████████████| 92/92 [00:00<00:00, 18426.82it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 92/92 [00:00<00:00, 46008.82it/s]\n",
      "Processing text_left with extend: 100%|█████████████████████████████████████████████| 95/95 [00:00<00:00, 96246.11it/s]\n",
      "Processing text_right with extend: 100%|████████████████████████████████████████████| 92/92 [00:00<00:00, 30629.94it/s]\n",
      "Building Vocabulary from a datapack.: 100%|██████████████████████████████████████| 933/933 [00:00<00:00, 233419.96it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 95/95 [00:00<00:00, 177.67it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 92/92 [00:00<00:00, 192.17it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 92/92 [00:00<00:00, 45964.98it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 95/95 [00:00<00:00, 31623.72it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 92/92 [00:00<00:00, 92336.92it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 95/95 [00:00<00:00, 47418.65it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 92/92 [00:00<00:00, 92006.67it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 50/50 [00:00<00:00, 193.91it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 48/48 [00:00<00:00, 185.43it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 48/48 [00:00<00:00, 24027.52it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 50/50 [00:00<00:00, 16674.50it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 48/48 [00:00<00:00, 48106.71it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 50/50 [00:00<00:00, 10012.66it/s]\n",
      "Processing length_right with len: 100%|██████████████████████████████████████████████| 48/48 [00:00<00:00, 6006.52it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 29/29 [00:00<00:00, 145.81it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 30/30 [00:00<00:00, 164.03it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 30/30 [00:00<00:00, 15022.58it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 29/29 [00:00<00:00, 14473.44it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 30/30 [00:00<00:00, 30073.88it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 29/29 [00:00<00:00, 29183.02it/s]\n",
      "Processing length_right with len: 100%|██████████████████████████████████████████████| 30/30 [00:00<00:00, 7481.37it/s]\n"
     ]
    }
   ],
   "source": [
    "train_pack_processed = preprocessor.fit_transform(train_pack_raw)\n",
    "dev_pack_processed = preprocessor.transform(dev_pack_raw)\n",
    "test_pack_processed = preprocessor.transform(test_pack_raw)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 生成训练数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "trainset = mz.dataloader.Dataset(\n",
    "    data_pack=train_pack_processed,\n",
    "    mode='pair',\n",
    "    num_dup=2,\n",
    "    num_neg=1\n",
    ")\n",
    "devset = mz.dataloader.Dataset(\n",
    "    data_pack=dev_pack_processed\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 生成管道"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "padding_callback = mz.models.aNMM.get_default_padding_callback()\n",
    "\n",
    "trainloader = mz.dataloader.DataLoader(\n",
    "    dataset=trainset,\n",
    "    stage='train',\n",
    "    callback=padding_callback,\n",
    ")\n",
    "devloader = mz.dataloader.DataLoader(\n",
    "    dataset=devset,\n",
    "    stage='dev',\n",
    "    callback=padding_callback,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 定义模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "aNMM(\n",
      "  (embedding): Embedding(332, 100, padding_idx=0)\n",
      "  (matching): Matching()\n",
      "  (hidden_layers): Sequential(\n",
      "    (0): Sequential(\n",
      "      (0): Linear(in_features=200, out_features=100, bias=True)\n",
      "      (1): ReLU()\n",
      "    )\n",
      "    (1): Sequential(\n",
      "      (0): Linear(in_features=100, out_features=1, bias=True)\n",
      "      (1): ReLU()\n",
      "    )\n",
      "  )\n",
      "  (q_attention): Attention(\n",
      "    (linear): Linear(in_features=100, out_features=1, bias=False)\n",
      "  )\n",
      "  (dropout): Dropout(p=0.1, inplace=False)\n",
      "  (out): Linear(in_features=1, out_features=1, bias=True)\n",
      ")\n"
     ]
    }
   ],
   "source": [
    "model = mz.models.aNMM()\n",
    "model.params['task'] = ranking_task\n",
    "model.params[\"embedding_output_dim\"]=100\n",
    "model.params[\"embedding_input_dim\"]=preprocessor.context[\"embedding_input_dim\"]\n",
    "model.params['dropout_rate'] = 0.1\n",
    "model.build()\n",
    "print(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 模型训练"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6c6ec25929fe4d3f9d7cb33d41b03473",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-1 Loss-0.993]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1622 - normalized_discounted_cumulative_gain@5(0.0): 0.1622 - mean_average_precision(0.0): 0.1622\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9907890548144cc4bc097f1419b54090",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\r",
      "[Iter-2 Loss-0.993]:\n",
      "\r",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1622 - normalized_discounted_cumulative_gain@5(0.0): 0.1622 - mean_average_precision(0.0): 0.1622\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5d3ca52dc6334aab9acd07620d452504",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-3 Loss-0.992]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1622 - normalized_discounted_cumulative_gain@5(0.0): 0.1622 - mean_average_precision(0.0): 0.1622\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "eb55a42d6380409698280e50bab112dc",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-4 Loss-0.991]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1622 - normalized_discounted_cumulative_gain@5(0.0): 0.1622 - mean_average_precision(0.0): 0.1622\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5be00c8d2d30445d98d4c46cbec7cff7",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-5 Loss-0.991]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1622 - normalized_discounted_cumulative_gain@5(0.0): 0.1622 - mean_average_precision(0.0): 0.1622\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8d591cb093924cb3bd993b517bc92056",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-6 Loss-0.989]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1622 - normalized_discounted_cumulative_gain@5(0.0): 0.1622 - mean_average_precision(0.0): 0.1622\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "999e361d2db241a09d1d0856a33a4357",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-7 Loss-0.992]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1622 - normalized_discounted_cumulative_gain@5(0.0): 0.1622 - mean_average_precision(0.0): 0.1622\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "28a24bc294504e0da8947adcfbc8dc9e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-8 Loss-0.989]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1622 - normalized_discounted_cumulative_gain@5(0.0): 0.1622 - mean_average_precision(0.0): 0.1622\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9795f7ad3268424a934ef519bc60eebd",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-9 Loss-0.990]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1622 - normalized_discounted_cumulative_gain@5(0.0): 0.1622 - mean_average_precision(0.0): 0.1622\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5c998b88c4f84834991e1aff75f99d95",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-10 Loss-0.988]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.1622 - normalized_discounted_cumulative_gain@5(0.0): 0.1622 - mean_average_precision(0.0): 0.1622\n",
      "\n",
      "Cost time: 3.42104434967041s\n"
     ]
    }
   ],
   "source": [
    "optimizer = torch.optim.Adam(model.parameters(), lr = 3e-4)\n",
    "\n",
    "trainer = mz.trainers.Trainer(\n",
    "    model=model,\n",
    "    optimizer=optimizer,\n",
    "    trainloader=trainloader,\n",
    "    validloader=devloader,\n",
    "    validate_interval=None,\n",
    "    epochs=10\n",
    ")\n",
    "\n",
    "trainer.run()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Install"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于mzcn是依赖于matchzoo-py模型，所以一共有两种途径安装mzcn"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Install MatchZoo-py from Pypi:\n",
    "pip install mzcn"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Install MatchZoo-py from the Github source:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "git clone https://github.com/yingdajun/mzcn.git\n",
    "<br>\n",
    "cd mzcn\n",
    "<br>\n",
    "python setup.py install"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Citation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "本人是第一次写库包，水平有限，希望能给大家带来使用的帮助，如果有不足的地方请多指教\n",
    "这里是所有引用过的库包"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## matchzoo-py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "@inproceedings{Guo:2019:MLP:3331184.3331403,\n",
    " author = {Guo, Jiafeng and Fan, Yixing and Ji, Xiang and Cheng, Xueqi},\n",
    " title = {MatchZoo: A Learning, Practicing, and Developing System for Neural Text Matching},\n",
    " booktitle = {Proceedings of the 42Nd International ACM SIGIR Conference on Research and Development in Information Retrieval},\n",
    " series = {SIGIR'19},\n",
    " year = {2019},\n",
    " isbn = {978-1-4503-6172-9},\n",
    " location = {Paris, France},\n",
    " pages = {1297--1300},\n",
    " numpages = {4},\n",
    " url = {http://doi.acm.org/10.1145/3331184.3331403},\n",
    " doi = {10.1145/3331184.3331403},\n",
    " acmid = {3331403},\n",
    " publisher = {ACM},\n",
    " address = {New York, NY, USA},\n",
    " keywords = {matchzoo, neural network, text matching},\n",
    "} "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## CSDN的作者：SK-Berry的博文"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "https://blog.csdn.net/sk_berry/article/details/104984599"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
